﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ADA.Presentation.PRL.Account;
using ADA.Presentation.PRL.MarketNews;
using ADA.Presentation.PRL.Trading;
using ADA.Entity;
using ADA.Business;
using System.IO;

namespace ADA.Presentation
{
    public partial class MainForm : Form
    {
        public Admin ad;
        Form loginForm;
        bool logout;

        public MainForm(Admin Ad, Form LoginForm)
        {
            loginForm = LoginForm;
            ad = Ad;
            logout = false;
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            lblAdminName.Text = ad.Name;
            dgvAdminAcc.MultiSelect = false;
            dgvUserAcc.MultiSelect = false;
            dgvUserPost.MultiSelect = false;
            dgvRice.MultiSelect = false;
            dgvRicePrice.MultiSelect = false;
            dgvNews.MultiSelect = false;
            tabControl.SelectTab(1);
        }

        private void linkChangePass_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            new ChangePassForm(ad).ShowDialog();
        }

        private void linkLogout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DialogResult result = MessageBox.Show(Common.MESSAGE_CONFIRM_LOG_OUT, "Confirm", MessageBoxButtons.OKCancel);
            if (result == DialogResult.OK)
            {
                loginForm.Show();
                logout = true;
                this.Close();
            }
        }

        private void tabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            TabPage current = (sender as TabControl).SelectedTab;
            switch (current.Name)
            {
                case "tabAdminAccount":
                    {
                        if (ad.Name.Equals("superadmin") == false)
                        {
                            MessageBox.Show(Common.MESSAGE_ERROR_NOT_SUPERADMIN);
                            tabControl.SelectTab(1);
                            return;
                        }
                        LoadTabPage_AdminAccount();
                    }
                    break;

                case "tabUserAccount":
                    {
                        LoadTabPage_UserAccount();
                    }
                    break;

                case "tabUserPost":
                    {
                        LoadTabPage_UserPost();
                    }
                    break;

                case "tabRiceInfomation":
                    {
                        LoadTabPage_RiceInfomation();
                    }
                    break;

                case "tabRicePrice":
                    {
                        LoadTabPage_RicePrice();
                    }
                    break;

                case "tabMarketNews":
                    {
                        LoadTabPage_MarketNews();
                    }
                    break;
            }
        }
        
        private void btnAddAdminAcc_Click(object sender, EventArgs e)
        {
            new AddAdminAccForm(this).ShowDialog();
        }

        private void btnDeleteAdminAcc_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvAdminAcc) == false) return;
            DialogResult confirmDel = MessageBox.Show(Common.MESSAGE_CONFIRM_DELETE, "Confirm", MessageBoxButtons.OKCancel);
            if (confirmDel == DialogResult.Cancel) return;
            short adminID = Convert.ToInt16(dgvAdminAcc.SelectedRows[0].Cells[0].Value);
            string message;
            BOLAccount bolAcc = new BOLAccount();
            if (bolAcc.deleteAdmin(adminID, out message) == true)
            {
                dgvAdminAcc.Rows.RemoveAt(dgvAdminAcc.SelectedRows[0].Index);
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnShowUserAcc_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvUserAcc) == false) return;
            long userID = Convert.ToInt64(dgvUserAcc.SelectedRows[0].Cells[0].Value);
            new UserAccDetailForm(this ,userID).ShowDialog();
        }

        public void btnDeleteUserAcc_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvUserAcc) == false) return;
            DialogResult confirmDel = MessageBox.Show(Common.MESSAGE_CONFIRM_DELETE, "Confirm", MessageBoxButtons.OKCancel);
            if (confirmDel == DialogResult.Cancel) return;
            string message;
            BOLAccount bolAcc = new BOLAccount();
            DataTable tblUser = new DataTable();
            long userID = Convert.ToInt64(dgvUserAcc.SelectedRows[0].Cells[0].Value);
            if (bolAcc.viewUserDetail(userID, out tblUser, out message) == true)
            {
                if (bolAcc.deleteUser(userID, out message) == true)
                {
                    if (tblUser.Rows.Count == 1)
                    {
                        string path =Path.GetFileName(Convert.ToString(tblUser.Rows[0]["ProfilePicture"]).Trim());
                        if (path.Equals(Common.DEFAULT_PROFILE_IMAGE_NAME) == false)
                        {
                            path = Common.URL_PROFILE_IMAGE + path;
                            if (System.IO.File.Exists(path))
                            {
                                try
                                {
                                    System.IO.File.Delete(path);
                                }
                                catch (Exception ex)
                                {
                                    message = ex.Message;
                                    MessageBox.Show(message);
                                    return;
                                }
                            }
                        }
                    }
                    dgvUserAcc.Rows.RemoveAt(dgvUserAcc.SelectedRows[0].Index);
                }
                else
                {
                    MessageBox.Show(message);
                }
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnShowUserPost_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvUserPost) == false) return;
            long postID = Convert.ToInt64(dgvUserPost.SelectedRows[0].Cells[0].Value);
            new UserPostDetailForm(this,postID).ShowDialog();
        }

        public void btnDeleteUserPost_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvUserPost) == false) return;
            DialogResult confirmDel = MessageBox.Show(Common.MESSAGE_CONFIRM_DELETE, "Confirm", MessageBoxButtons.OKCancel);
            if (confirmDel == DialogResult.Cancel) return;
            string message;
            BOLTrading bolTrading = new BOLTrading();
            long postID = Convert.ToInt64(dgvUserPost.SelectedRows[0].Cells[0].Value);
            if (bolTrading.deletePost(postID, out message) == true)
            {
                dgvUserPost.Rows.RemoveAt(dgvUserPost.SelectedRows[0].Index);
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnShowRice_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvRice) == false) return;
            int riceID = Convert.ToInt32(dgvRice.SelectedRows[0].Cells[0].Value);
            new ShowRiceForm(this, riceID).ShowDialog();
        }

        private void btnAddRice_Click(object sender, EventArgs e)
        {
            new EditRiceForm(this).ShowDialog();
        }

        public void btnEditRice_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvRice) == false) return;
            int riceID = Convert.ToInt32(dgvRice.SelectedRows[0].Cells[0].Value);
            new EditRiceForm(riceID, this).ShowDialog();
        }

        public void btnDeleteRice_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvRice) == false) return;
            DialogResult confirmDel = MessageBox.Show(Common.MESSAGE_CONFIRM_DELETE, "Confirm", MessageBoxButtons.OKCancel);
            if (confirmDel == DialogResult.Cancel) return;
            Rice rice = new Rice();
            rice.ID = Convert.ToInt32(dgvRice.SelectedRows[0].Cells[0].Value);
            string message;
            BOLNews bolNews = new BOLNews();
            if (bolNews.getRiceInfo(rice.ID, out rice, out message) == true)
            {
                if (bolNews.deleteRice(rice.ID, out message) == true)
                {
                    // Delete a file by using File class static method... 
                    if (Path.GetFileName(rice.Image).Equals(Common.DEFAULT_RICE_IMAGE_NAME) == false)
                    {
                        string path = Common.URL_RICE + Path.GetFileName(rice.Image);
                        if (System.IO.File.Exists(path))
                        {
                            try
                            {
                                System.IO.File.Delete(path);
                            }
                            catch (Exception ex)
                            {
                                message = ex.Message;
                                MessageBox.Show(message);
                                return;
                            }
                        }
                    }
                    dgvRice.Rows.RemoveAt(dgvRice.SelectedRows[0].Index);
                }
                else
                {
                    MessageBox.Show(message);
                }
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnUpdateRicePrice_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvRicePrice) == false) return;
            string message;
            BOLNews bolNews = new BOLNews();
            int riceID = Convert.ToInt32(dgvRicePrice.SelectedRows[0].Cells[0].Value);
            int newPrice;
            try
            {
                newPrice = Convert.ToInt32(tbxUpdatePrice.Text.Trim());
                if (newPrice < 0 || newPrice > 1000000)
                {
                    MessageBox.Show(Common.MESSAGE_ERROR_PRICE_RANGE);
                    return;
                }
            }
            catch
            {
                MessageBox.Show(Common.MESSAGE_ERROR_IS_NUMBER);
                return;
            }
            if (bolNews.updatePrice(riceID, newPrice, out message) == true)
            {
                dgvRicePrice.SelectedRows[0].Cells[3].Value = newPrice.ToString();
                tbxUpdatePrice.Text = "";
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnUpdatePercent_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvRicePrice) == false) return;
            string message;
            BOLNews bolNews = new BOLNews();
            int riceID = Convert.ToInt32(dgvRicePrice.SelectedRows[0].Cells[0].Value);
            int newPercent;
            try
            {
                newPercent = Convert.ToInt32(tbxPercent.Text.Trim());
                if (newPercent < 0 || newPercent > 100)
                {
                    MessageBox.Show(Common.MESSAGE_ERROR_PERCENT_RANGE);
                    return;
                }
            }
            catch
            {
                MessageBox.Show(Common.MESSAGE_ERROR_IS_NUMBER);
                return;
            }
            if (bolNews.updatePercent(riceID, newPercent, out message) == true)
            {
                dgvRicePrice.SelectedRows[0].Cells[4].Value = newPercent.ToString();
                tbxUpdatePrice.Text = "";
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnShowNews_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvNews) == false) return;
            int newsID = Convert.ToInt32(dgvNews.SelectedRows[0].Cells[0].Value);
            new ShowMarketNewsForm(this, newsID).ShowDialog();
        }
        
        private void btnAddNews_Click(object sender, EventArgs e)
        {
            new EditMarketNewsForm(this).ShowDialog();
        }

        public void btnEditNews_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvNews) == false) return;
            int newsID = Convert.ToInt32(dgvNews.SelectedRows[0].Cells[0].Value);
            new EditMarketNewsForm(newsID, this).ShowDialog();
        }

        public void btnDeleteNews_Click(object sender, EventArgs e)
        {
            if (checkSelect(dgvNews) == false) return;
            DialogResult confirmDel = MessageBox.Show(Common.MESSAGE_CONFIRM_DELETE, "Confirm", MessageBoxButtons.OKCancel);
            if (confirmDel == DialogResult.Cancel) return;
            News news = new News();
            news.ID = Convert.ToInt32(dgvNews.SelectedRows[0].Cells[0].Value);
            string message;
            BOLNews bolNews = new BOLNews();
            if (bolNews.getNewsInfo(news.ID, out news, out message) == true)
            {
                if (bolNews.deleteNews(news.ID, out message) == true)
                {
                    if (Path.GetFileName(news.Image).Equals(Common.DEFAULT_NEWS_IMAGE_NAME) == false)
                    {
                        string path = Common.URL_NEWS + Path.GetFileName(news.Image);
                        if (System.IO.File.Exists(path))
                        {
                            try
                            {
                                System.IO.File.Delete(path);
                            }
                            catch (Exception ex)
                            {
                                message = ex.Message;
                                MessageBox.Show(message);
                                return;
                            }
                        }
                    }
                    dgvNews.Rows.RemoveAt(dgvNews.SelectedRows[0].Index);
                }
                else
                {
                    MessageBox.Show(message);
                }
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnSearchAdminAcc_Click(object sender, EventArgs e)
        {
            search(tbxSearchAdminAcc, cbxSearchAdminAcc, dgvAdminAcc);
        }

        private void btnSearchUserAcc_Click(object sender, EventArgs e)
        {
            search(tbxSearchUserAcc, cbxSearchUserAcc, dgvUserAcc);
        }

        private void btnSearchUserPost_Click(object sender, EventArgs e)
        {
            search(tbxSearchUserPost, cbxSearchUserPost, dgvUserPost);
        }

        private void tbnSearchRiceInfomation_Click(object sender, EventArgs e)
        {
            search(tbxSearchRiceInfomation, cbxSearchRiceInfomation, dgvRice);
        }

        private void btnSearchRicePrice_Click(object sender, EventArgs e)
        {
            search(tbxSearchRicePrice, cbxSearchRicePrice, dgvRicePrice);
        }

        private void btnSearchMarketNews_Click(object sender, EventArgs e)
        {
            search(tbxSearchMarketNews, cbxSearchMarketNews, dgvNews);
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (logout == false) loginForm.Close();
        }

        /// <summary>
        /// ///////////////////////////////////////////////////////////
        /// </summary>

        public bool checkSelect(DataGridView dgv)
        {
            if (dgv.SelectedRows.Count == 0)
            {
                MessageBox.Show(Common.MESSAGE_ERROR_NO_SELECT_ROW);
                return false;
            }
            if (dgv.SelectedRows.Count > 1)
            {
                MessageBox.Show(Common.MESSAGE_ERROR_SELECT_MORE_THAN_ONE_ROW);
                return false;
            }
            return true;
        }

        public void LoadTabPage_AdminAccount()
        {
            cbxSearchAdminAcc.SelectedIndex = 0;
            tbxSearchAdminAcc.Text = "";

            DataTable tblAdmin = new DataTable();
            string message = "";
            BOLAccount bolAcc = new BOLAccount();
            if (bolAcc.viewAllAdmin(out tblAdmin, out message))
            {
                dgvAdminAcc.AutoGenerateColumns = false;
                dgvAdminAcc.DataSource = tblAdmin;
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        public void LoadTabPage_UserAccount()
        {
            cbxSearchUserAcc.SelectedIndex = 0;
            tbxSearchUserAcc.Text = "";

            DataTable tblUser = new DataTable();
            string message = "";
            BOLAccount bolAcc = new BOLAccount();
            if (bolAcc.viewAllUser(out tblUser, out message))
            {
                dgvUserAcc.AutoGenerateColumns = false;
                dgvUserAcc.DataSource = tblUser;
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        public void LoadTabPage_UserPost()
        {
            cbxSearchUserPost.SelectedIndex = 0;
            tbxSearchUserPost.Text = "";

            DataTable tblPost = new DataTable();
            string message = "";
            BOLTrading bolTrading = new BOLTrading();
            if (bolTrading.viewAllPost(out tblPost, out message))
            {
                dgvUserPost.AutoGenerateColumns = false;
                dgvUserPost.DataSource = tblPost;
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        public void LoadTabPage_RiceInfomation()
        {
            cbxSearchRiceInfomation.SelectedIndex = 0;
            tbxSearchRiceInfomation.Text = "";

            DataTable tblRice = new DataTable();
            string message = "";
            BOLNews bolNews = new BOLNews();
            if (bolNews.viewAllRice(out tblRice, out message))
            {
                dgvRice.AutoGenerateColumns = false;
                dgvRice.DataSource = tblRice;
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        public void LoadTabPage_RicePrice()
        {
            cbxSearchRicePrice.SelectedIndex = 0;
            tbxSearchRicePrice.Text = "";
            tbxPercent.Text = "";
            tbxUpdatePrice.Text = "";

            DataTable tblRicePrice = new DataTable();
            string message = "";
            BOLNews bolNews = new BOLNews();
            if (bolNews.viewAllRicePrice(out tblRicePrice, out message))
            {
                dgvRicePrice.AutoGenerateColumns = false;
                dgvRicePrice.DataSource = tblRicePrice;
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        public void LoadTabPage_MarketNews()
        {
            cbxSearchMarketNews.SelectedIndex = 0;
            tbxSearchMarketNews.Text = "";

            DataTable tblNews = new DataTable();
            string message = "";
            BOLNews bolNews = new BOLNews();
            if (bolNews.viewAllNews(out tblNews, out message))
            {
                dgvNews.AutoGenerateColumns = false;
                dgvNews.DataSource = tblNews;
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void search(TextBox tbx, ComboBox cbx, DataGridView dgv)
        {
            string search = tbx.Text.Trim();
            int searchConditionIndex = cbx.SelectedIndex;
            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                string value = dgv.Rows[i].Cells[searchConditionIndex].Value.ToString().Trim();
                if (System.Text.RegularExpressions.Regex.IsMatch(value, search, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    cancelSelected(dgv);
                    dgv.Rows[i].Selected = true;
                }
            }
        }

        private void cancelSelected(DataGridView dgv)
        {
            if (dgv.SelectedRows.Count > 0)
            {
                dgv.SelectedRows[0].Selected = false;
            }
            if (dgv.SelectedCells.Count > 0)
            {
                dgv.SelectedCells[0].Selected = false;
            }
            if (dgv.SelectedColumns.Count > 0)
            {
                dgv.SelectedColumns[0].Selected = false;
            }
        }
    }
}
